//
// 全局 入口地址
//
//

import { JsonRpc } from './jsonrpc.js'
import { Controllers } from './controllers/index.js'
import { Environment } from './env.js'

export class OdooJSRPC {
  constructor(payload) {
    const { debug, run_by_server } = payload
    this.debug = debug
    this.run_by_server_of_config = run_by_server
    this.run_by_server = false

    const { Request, baseURL, timeout, messageError } = payload
    this.baseURL = baseURL

    const jsonrpc = new JsonRpc({ Request, baseURL, timeout, messageError })
    const api = new Controllers({ jsonrpc })
    const env = new Environment({ rpc: this })

    this.web = api.web
    this.env = env

    this._addons_models = []
  }

  async after_session() {
    if (!this.run_by_server_of_config) {
      return
    }

    const modules = await this.env.model('ir.module.module').search_read({
      domain: [
        ['state', '!=', 'uninstalled'],
        ['name', '=', 'web_for_odoojs']
      ],
      fields: ['name']
    })

    // console.log('modules', modules)
    if (modules.length) {
      this.run_by_server = this.run_by_server_of_config
    }
  }

  async login({ db, login, password }) {
    const payload = { db, login, password }
    const info = await this.web.session.authenticate(payload)
    if (info) {
      await this.after_session()
    }
    return info
  }

  async session_check() {
    const info = await this.web.session.session_check()
    if (info) {
      await this.after_session()
    }
    return info
  }

  async logout() {
    const info = await this.web.session.logout()
    return info
  }
}
